package sf.database.dialect.sqlserver;

import com.querydsl.sql.SQLServer2005Templates;
import com.querydsl.sql.SQLTemplates;
import sf.database.dialect.Keywords;
import sf.database.meta.TableMapping;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SQLServer2005Dialect extends SqlServerDialect {
    private static SQLTemplates sqlTemplates = SQLServer2005Templates.DEFAULT;

    public SQLTemplates getQueryDslDialect() {
        return sqlTemplates;
    }

    public SQLServer2005Dialect() {
        this.keywords.addAll(Keywords.SQLSERVER2005);
    }

    @Override
    public String sqlPageList(String sql, long offset, int limit) {
        long pageEnd = offset + limit - 1;

        sql = sql.replaceFirst("(?i)select(\\s+distinct\\s+)?", "$0 top(" + pageEnd + ") ");

        int capacity = sql.length() + 190;
        StringBuilder builder = new StringBuilder(capacity);
        builder.append("with query as ( select inner_query.*, row_number() over (order by current_timestamp) as rn from ( ");
        builder.append(sql);
        builder.append(" ) inner_query ) select * from query where rn between ");
        builder.append(offset).append(" and ").append(pageEnd);

        return builder.toString();
    }

    public List<String> getIndexNames(TableMapping en, Connection conn) throws SQLException {
        List<String> names = new ArrayList<String>();
        String showIndexs = "SELECT i.name FROM sys.indexes AS i "
                + "INNER JOIN sys.tables AS o ON i.[object_id] = o.[object_id] "
                + "WHERE  o.name = '" + en.getTableName() + "' AND i.is_primary_key = 0";

        PreparedStatement ppstat = conn.prepareStatement(showIndexs);
        ResultSet rest = ppstat.executeQuery();
        while (rest.next()) {
            String index = rest.getString(1);
            names.add(index);
        }
        return names;
    }
}
